<?php  if (!defined('BASEPATH')) exit('No direct script access allowed');

function shorten_link($string) {
	$text_word_maxlength = 55;
	if(count($string) == 2) { $pre = ""; $url = $string[1]; }
	else { $pre = $string[1]; $url = $string[2]; }
	$shortened_url = $url;
	if (strlen($url) > $text_word_maxlength) $shortened_url = substr($url, 0, ($text_word_maxlength/2)) . "..." . substr($url, - ($text_word_maxlength-3-$text_word_maxlength/2));
	return $pre."<a target=\"fromForum\" href=\"".$url."\">".$shortened_url."</a>";
}
 
function parse_code($string) {
	$string = $string[1];
	$string = str_replace('<br />','',$string);
	$string = '</p><pre><span class="code">'.$string.'</span></pre><p>';
	return $string;
}
 

function bbcode($string) {
	$string = preg_replace("#\[b\](.+?)\[/b\]#is", "<b>\\1</b>", $string);
	$string = preg_replace("#\[i\](.+?)\[/i\]#is", "<i>\\1</i>", $string);
	$string = preg_replace("#\[u\](.+?)\[/u\]#is", "<u>\\1</u>", $string);
	$string = preg_replace("#\[link\]www\.(.+?)\[/link\]#is", "<a href=\"http://www.\\1\">www.\\1</a>", $string);
	$string = preg_replace_callback("#\[link\](.+?)\[/link\]#is", "shorten_link", $string);
	$string = preg_replace("#\[link=(.+?)\](.+?)\[/link\]#is", "<a href=\"\\1\">\\2</a>", $string);
	$string = preg_replace("#\[url\]www\.(.+?)\[/url\]#is", "<a href=\"http://www.\\1\">www.\\1</a>", $string);
	$string = preg_replace_callback("#\[url\](.+?)\[/url\]#is", "shorten_link", $string);
	$string = preg_replace("#\[url=(.+?)\](.+?)\[/url\]#is", "<a href=\"\\1\">\\2</a>", $string);
	$string = preg_replace_callback("#\[code\](.+?)\[/code\]#is", "parse_code", $string);
	$string = preg_replace("#\[msg\](.+?)\[/msg\]#is", "<a href=\"".basename($_SERVER['PHP_SELF'])."?id=\\1\">\\1</a>", $string);
	$string = preg_replace("#\[msg=(.+?)\](.+?)\[/msg\]#is", "<a href=\"".basename($_SERVER['PHP_SELF'])."?id=\\1\">\\2</a>", $string);
	$string = preg_replace("#\[img\](.+?)\[/img\]#is", "<img src=\"\\1\" alt=\"[image]\" style=\"margin: 5px 0px 5px 0px\" />", $string);
	$string = preg_replace("#\[img\|left\](.+?)\[/img\]#is", "<img src=\"\\1\" alt=\"[image]\" style=\"float: left; margin: 0px 5px 5px 0px\" />", $string);
	$string = preg_replace("#\[img\|right\](.+?)\[/img\]#is", "<img src=\"\\1\" alt=\"[image]\" style=\"float: right; margin: 0px 0px 5px 5px\" />", $string);
	
	// [youtube]ID[/youtube]
	$youtube = "<p class=\"youtube\"><a href=\"http://youtube.com/v/\\1&hl=de&rel=0&color1=0x234900&color2=0x4e9e00\">http://youtube.com/v/\\1</a></p>";
	$string = preg_replace("#\[youtube\](.+?)\[/youtube\]#is", $youtube, $string);
	
	$string = str_replace("\n","<br/>",$string);
	return $string;
}

